namespace Tycho.Parser.Peg {
    public class IndentationProduction : Production {
        public static Terminal CreateTerminal () {
            return new Terminal (new IndentationProduction ());
        }

        protected override ParseResult ReallyParse (char[] source, int startIndex, ParseContext context, string sourceString, ParseEnvironment parseEnvironment) {
            int index = Whitespace.SkipWhitespace (source, startIndex);

            int startOfLine = -1;
            while (IsNewLine (source, ref index)) {
                startOfLine = index;

                index = Whitespace.SkipWhitespace (source, index);
            }

            if (startOfLine > 0) {
                string indent = GetIndent (source, index, startOfLine);

                var sinfo = parseEnvironment.SourceFileInformation.CreateSourceInformation (startIndex, index - startIndex);
                var term = new IndentationTerm (indent, sinfo);
                var newContext = context.Clone ();
                newContext.LastIndent = indent;
                return new ParseResult (index, term, newContext);
            } else {
                return null;
            }
        }

        private static string GetIndent (char[] source, int index, int startOfLine) {
            if (index >= source.Length) {
                return null;
            } else {
                return new string (source, startOfLine, index - startOfLine);
            }
        }

        private static bool IsNewLine (char[] source, ref int index) {
            if (index < source.Length - 1
                && source[index] == '\r'
                && source[index + 1] == '\n') {
                index += 2;
                return true;
            }

            if (index < source.Length
                && source[index] == '\n') {
                index++;
                return true;
            }

            return false;
        }
    }
}